<template>
  <div class="framework1">
    <!--    全部表格-->
    <div class="framework2">

      <!--      上半部分表格-->
      <div>

        <div class="header">数据字典->违法行为</div>

        <div class="button_group">
          <el-button type="primary" icon="DocumentAdd" v-if="permissionIsShow.add"
            @click="addLawsAndRegulations">新增法规</el-button>
          <el-input v-model="search" placeholder="搜索违法行为" style="width: 250px;margin-left: 15px;margin-right: 15px"
            clearable></el-input>
          <el-button type="primary" icon="Search" @click="searchLawsAndRegulations()">搜索</el-button>
        </div>
        <div style="height: calc(100vh - 134px)">
          <el-table :data="lawsAndRegulationsList" :header-cell-style="{ background: '#f4f3f9' }" highlight-current-row
            style="width:100%; height: calc(100% - 68px); background:#f4f3f9" border>
            <el-table-column align="center" prop="illegalAct" label="违法行为" width="200"></el-table-column>
            <el-table-column align="center" prop="illegalTermsString" label="违反条款" width="300">
              <template v-slot="{ row }">
                <div class="formatted-text">{{ row.illegalTermsString }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="illegalBasisString" label="处罚依据" width="300">
              <template v-slot="{ row }">
                <div class="formatted-text">{{ row.illegalBasisString }}</div>
              </template>
            </el-table-column>

            <el-table-column align="center" label="较轻情形">
              <el-table-column align="center" prop="slightPlotConsequences" label="违法情节和后果"
                width="200"></el-table-column>
              <el-table-column align="center" prop="slightPunishmentStandards" label="处罚标准"
                width="200"></el-table-column>
            </el-table-column>

            <el-table-column align="center" label="一般情形">
              <el-table-column align="center" prop="generalPlotConsequences" label="违法情节和后果"
                width="200"></el-table-column>
              <el-table-column align="center" prop="generalPunishmentStandards" label="处罚标准"
                width="200"></el-table-column>
            </el-table-column>

            <el-table-column align="center" label="严重情形">
              <el-table-column align="center" prop="seriousPlotConsequences" label="违法情节和后果"
                width="200"></el-table-column>
              <el-table-column align="center" prop="seriousPunishmentStandards" label="处罚标准"
                width="200"></el-table-column>
            </el-table-column>
            <el-table-column align="center" prop="operate" label="操作" width="200" fixed="right"
              v-if="permissionIsShow.edit || permissionIsShow.delete">
              <template v-slot="scope">
                <el-button type="primary" size="small" icon="Edit" v-if="permissionIsShow.edit"
                  @click.native.stop="editRoleData(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" icon="Delete" v-if="permissionIsShow.delete"
                  @click.native.stop="deleteRoleData(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--      分页1-->
          <div class="footer">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 新增/编辑 弹窗 -->
    <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" :title="isEdit ? '编辑' : '新增'"
      :before-close="CloseAddLawsAndRegulations" width="900px">
      <el-form>
        <el-form-item>
          违法行为：
          <el-input type="textarea" v-model="lawsAndRegulationsForm.illegalAct" placeholder="请输入违法行为"></el-input>
        </el-form-item>

        违反条款：<el-button type="primary" style="margin-bottom: 10px;" @click="addIllegalTerms">新增一条</el-button>
        <el-form-item v-for="(item, index) in inputIllegalTermsObject" :key="index">
          <div style="margin-bottom: 10px;">
            <el-select v-model="item.lawType" filterable allow-create clearable placeholder="法律类型，例：【行政法规】"
              style="width: 390px; margin-right: 10px;" @change="(val) => handlelawTypeChange(item, val)"
              @blur="handlelawTypeBlur(item, $event)" @clear="clearLawsFields(item, 'type')">
              <el-option v-for="type in uniquelawTypes" :key="type" :label="type" :value="type" />
            </el-select>

            <el-select v-model="item.lawName" filterable allow-create clearable placeholder="法律名称，例：《城市市容和环境卫生管理条例》"
              style="width: 390px;  margin-right: 10px;" @change="(val) => handlelawNameChange(item, val)"
              @blur="handlelawNameBlur(item, $event)" :disabled="!item.lawType" @clear="clearLawsFields(item, null)">
              <el-option v-for="low in filteredLowsByType(item.lawType)" :key="low.id" :label="low.name"
                :value="low.name" />
            </el-select>
            <!-- 删除按钮 -->
            <el-button v-if="inputIllegalTermsObject.length > 1" type="danger" icon="Delete"
              @click="removeIllegalTerms(index)" />

          </div>
          <div style="margin-bottom: 10px;">
            <el-select v-model="item.article" filterable allow-create clearable placeholder="第几条"
              style="width: 200px; margin-right: 10px" @change="(val) => handleArticleChange(item, val)"
              @blur="handleArticleBlur(item, $event)" :disabled="isArticleEditable(item)"
              @clear="clearDependentFields(item, 1)">
              <el-option v-for="article in articleList" :key="article" :label="article" :value="article" />
            </el-select>
            <el-select v-model="item.paragraph" filterable allow-create clearable placeholder="第几款"
              style="width: 200px; margin-right: 10px" @change="(val) => handleParagraphChange(item, val)"
              @blur="handleParagraphBlur(item, $event)" :disabled="isParagraphEditable(item)"
              @clear="clearDependentFields(item, 2)">
              <el-option v-for="paragraph in paragraphList" :key="paragraph" :label="paragraph" :value="paragraph" />
            </el-select>
            <el-select v-model="item.subparagraph" filterable allow-create clearable placeholder="第几项"
              style="width: 200px; margin-right: 10px" @change="(val) => handleSubparagraphChange(item, val)"
              @blur="handleSubparagraphBlur(item, $event)" :disabled="isSubparagraphEditable(item)"
              @clear="clearDependentFields(item, 3)">
              <el-option v-for="subparagraph in subparagraphList" :key="subparagraph" :label="subparagraph"
                :value="subparagraph" />
            </el-select>
            <el-select v-model="item.item" filterable allow-create clearable placeholder="第几目"
              style="width: 200px; margin-right: 10px" @change="(val) => handleItemChange(item, val)"
              @blur="handleItemBlur(item, $event)" :disabled="isItemEditable(item)"
              @clear="clearDependentFields(item, 4)">
              <el-option v-for="item in itemList" :key="item.id" :label="item.item" :value="item.item" />
            </el-select>
          </div>
          <el-input type="textarea" v-model="item.content" placeholder="请输入条款内容" :disabled="isContentEditable(item)" />
        </el-form-item>

        处罚依据：<el-button type="primary" style="margin-bottom: 10px;" @click="addIllegalBasis">新增一条</el-button>
        <el-form-item v-for="(item, index) in inputIllegalBasisObject" :key="index">
          <div style="margin-bottom: 10px;">
            <el-select v-model="item.lawType" filterable allow-create clearable placeholder="法律类型，例：【行政法规】"
              style="width: 390px; margin-right: 10px" @change="(val) => handlelawTypeChange(item, val)"
              @blur="handlelawTypeBlur(item, $event)" @clear="clearLawsFields(item, 'type')">
              <el-option v-for="type in uniquelawTypes" :key="type" :label="type" :value="type" />
            </el-select>

            <el-select v-model="item.lawName" filterable allow-create clearable placeholder="法律名称，例：《城市市容和环境卫生管理条例》"
              style="width: 390px; margin-right: 10px" @change="(val) => handlelawNameChange(item, val)"
              @blur="handlelawNameBlur(item, $event)" :disabled="!item.lawType" @clear="clearLawsFields(item, null)">
              <el-option v-for="low in filteredLowsByType(item.lawType)" :key="low.id" :label="low.name"
                :value="low.name" />
            </el-select>
            <!-- 删除按钮 -->
            <el-button v-if="inputIllegalBasisObject.length > 1" type="danger" icon="Delete"
              @click="removeIllegalBasis(index)" />
          </div>

          <div style="margin-bottom: 10px;">
            <el-select v-model="item.article" filterable allow-create clearable placeholder="第几条"
              style="width: 200px; margin-right: 10px" @change="(val) => handleArticleChange(item, val)"
              @blur="handleArticleBlur(item, $event)" :disabled="isArticleEditable(item)"
              @clear="clearDependentFields(item, 1)">
              <el-option v-for="article in articleList" :key="article" :label="article" :value="article" />
            </el-select>
            <el-select v-model="item.paragraph" filterable allow-create clearable placeholder="第几款"
              style="width: 200px; margin-right: 10px" @change="(val) => handleParagraphChange(item, val)"
              @blur="handleParagraphBlur(item, $event)" :disabled="isParagraphEditable(item)"
              @clear="clearDependentFields(item, 2)">
              <el-option v-for="paragraph in paragraphList" :key="paragraph" :label="paragraph" :value="paragraph" />
            </el-select>
            <el-select v-model="item.subparagraph" filterable allow-create clearable placeholder="第几项"
              style="width: 200px; margin-right: 10px" @change="(val) => handleSubparagraphChange(item, val)"
              @blur="handleSubparagraphBlur(item, $event)" :disabled="isSubparagraphEditable(item)"
              @clear="clearDependentFields(item, 3)">
              <el-option v-for="subparagraph in subparagraphList" :key="subparagraph" :label="subparagraph"
                :value="subparagraph" />
            </el-select>
            <el-select v-model="item.item" filterable allow-create clearable placeholder="第几目"
              style="width: 200px; margin-right: 10px" @change="(val) => handleItemChange(item, val)"
              @blur="handleItemBlur(item, $event)" :disabled="isItemEditable(item)"
              @clear="clearDependentFields(item, 4)">
              <el-option v-for="item in itemList" :key="item.id" :label="item.item" :value="item.item" />
            </el-select>
          </div>
          <el-input type="textarea" v-model="item.content" placeholder="请输入条款内容" :disabled="isContentEditable(item)" />

        </el-form-item>
        <el-form-item>
          较轻情形：
          <el-input type="textarea" placeholder="请输入较轻情形的违法情节和后果"
            v-model="lawsAndRegulationsForm.slightPlotConsequences"></el-input>
          <el-input type="textarea" placeholder="请输入较轻情形的处罚依据"
            v-model="lawsAndRegulationsForm.slightPunishmentStandards" style="margin-top: 10px;"></el-input>
        </el-form-item>
        <el-form-item>
          一般情形：
          <el-input type="textarea" placeholder="请输入一般情形的违法情节和后果"
            v-model="lawsAndRegulationsForm.generalPlotConsequences"></el-input>
          <el-input type="textarea" placeholder="请输入一般情形的处罚依据"
            v-model="lawsAndRegulationsForm.generalPunishmentStandards" style="margin-top: 10px;"></el-input>
        </el-form-item>
        <el-form-item>
          严重情形：
          <el-input type="textarea" placeholder="请输入严重情形的违法情节和后果"
            v-model="lawsAndRegulationsForm.seriousPlotConsequences"></el-input>
          <el-input type="textarea" placeholder="请输入严重情形的处罚依据"
            v-model="lawsAndRegulationsForm.seriousPunishmentStandards" style="margin-top: 10px;"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="CloseAddLawsAndRegulations">取消</el-button>
          <el-button type="primary" @click="saveLawsAndRegulations()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import SIdentify from "@/views/SIdentify.vue";
export default {
  name: "LawsAndRegulations",
  components: { SIdentify },
  data() {
    return {
      search: "", // 搜索匹配

      lawsAndRegulationsList: [], // 违法行为列表
      lowsList: [], // 法律列表
      articleList: [], // 第几条列表
      paragraphList: [], // 第几款列表
      subparagraphList: [], // 第几项列表
      itemList: [], // 第几目列表

      total: 0,
      pageSize: 5,
      pageNum: 1,

      dialogFormVisible: false, //新增弹窗控制
      isEdit: false, // 编辑标志
      inputIllegalTermsObject: [{
        id: null,
        lawsId: null, // 法律ID
        article: null, // 第几条
        paragraph: null, // 第几款
        subparagraph: null, // 第几项
        item: null, // 第几目
        lawName: null, // 法律名称
        lawType: null, // 法律类型
        content: null, // 条款内容
      }], // 输入的违反条款
      inputIllegalBasisObject: [{
        id: null,
        lawsId: null, // 法律ID
        article: null, // 第几条
        paragraph: null, // 第几款
        subparagraph: null, // 第几项
        item: null, // 第几目
        lawName: null, // 法律名称
        lawType: null, // 法律类型
        content: null, // 条款内容
      }], // 输入的处罚依据


      lawsAndRegulationsForm: {
        illegalAct: null, // 违法行为
        illegalTerms: null, // 下拉框选择违反条款的ID
        illegalTermsObject: [], // 输入的违反条款
        illegalBasis: null, // 下拉框选择处罚依据的ID
        illegalBasisObject: [], // 输入的处罚依据
        slightPlotConsequences: null, // 轻微违法情节和后果
        slightPunishmentStandards: null, // 轻微处罚标准
        generalPlotConsequences: null, // 一般违法情节和后果
        generalPunishmentStandards: null, // 一般处罚标准
        seriousPlotConsequences: null, // 严重违法情节和后果
        seriousPunishmentStandards: null, // 严重处罚标准
      },
      // 登录用户信息
      loginUserInfo: {
        id: '',
        responsibleScope: '', //查询范围
        roleLevel: '', //角色等级
        unitId: '', //内设部门ID
        userRole: '', //角色ID
        permissions: [], // 按钮路径（数据库中的path）
      },
      // 按钮权限
      permissionIsShow: {
        add: false,
        edit: false,
        delete: false,
      },
    }
  },
  created() {
    const info = JSON.parse(localStorage.getItem("user"));
    this.loginUserInfo = {
      id: Number(info.id),
      responsibleScope: info.responsibleScope, //查询范围
      roleLevel: Number(info.roleLevel),
      unitId: Number(info.unitId),
      userRole: Number(info.userRole),
      permissions: info.permissions.filter(item => Number(item.menuId) === 31).map(item => item.path),
    }
    this.permissionIsShow = {
      add: this.loginUserInfo.permissions.includes('lawsAndRegulations-add'),
      edit: this.loginUserInfo.permissions.includes('lawsAndRegulations-edit'),
      delete: this.loginUserInfo.permissions.includes('lawsAndRegulations-delete'),
    }
    this.load()
  },
  computed: {
    // 获取所有唯一的法律类型
    uniquelawTypes() {
      return [...new Set(this.lowsList.map(low => low.type))];
    },
  },
  methods: {
    // 获取数据
    load() {
      this.gettableData()
      this.getLowsList()
    },
    // 搜索
    searchLawsAndRegulations() {
      this.pageNum = 1;
      this.gettableData();
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.gettableData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.gettableData();
    },

    // 查询数据
    gettableData() {
      request.get("/laws-and-regulations/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          search: this.search,
        }
      }).then(res => {
        if (res.code == '200') {
          this.lawsAndRegulationsList = res.data.records
          this.total = res.data.total
        }
      })
    },
    // 获取法律列表数据
    getLowsList() {
      request.get("/laws/all").then(res => {
        if (res.code == '200') {
          this.lowsList = res.data
        }
      })
    },
    // 获取第几条数据
    getArticleList(item) {
      request.get("/term/getLevelData", {
        params: {
          level: 1,
          lowsId: item.lawsId,
        }
      }).then(res => {
        if (res.code == '200') {
          this.articleList = res.data.dataList
        }
      })
    },
    // 获取第几款数据
    getParagraphList(item) {
      request.get("/term/getLevelData", {
        params: {
          level: 2,
          lowsId: item.lawsId,
          article: item.article,
        }
      }).then(res => {
        if (res.code == '200') {
          this.paragraphList = res.data.dataList
          if (res.data.id !== null) {
            item.id = res.data.id;
            item.content = res.data.content;
          }
        }
      })
    },
    // 获取第几项数据
    getSubparagraphList(item) {
      request.get("/term/getLevelData", {
        params: {
          level: 3,
          lowsId: item.lawsId,
          article: item.article,
          paragraph: item.paragraph,
        }
      }).then(res => {
        if (res.code == '200') {
          this.subparagraphList = res.data.dataList
          if (res.data.id !== null) {
            item.id = res.data.id;
            item.content = res.data.content;
          }
        }
      })
    },
    // 获取第几目数据
    getItemList(item) {
      request.get("/term/getLevelData", {
        params: {
          level: 4,
          lowsId: item.lawsId,
          article: item.article,
          paragraph: item.paragraph,
          subparagraph: item.subparagraph,
        }
      }).then(res => {
        if (res.code == '200') {
          this.itemList = res.data.dataList
          if (res.data.id !== null) {
            item.id = res.data.id;
            item.content = res.data.content;
          }
        }
      })
    },
    clearLawsFields(item, level) {
      if (level === "type") {
        item.lawType = null;
      }
      item.lawName = null;
      item.lawsId = null;
      // 清空依赖字段
      this.clearDependentFields(item, 1);
    },
    // 清空依赖字段
    clearDependentFields(item, level) {
      // level表示从哪一级开始清空（1=条，2=款，3=项，4=目）
      if (level <= 1) {
        item.article = null;
      }
      if (level <= 2) {
        item.paragraph = null;
      }
      if (level <= 3) {
        item.subparagraph = null;
      }
      if (level <= 4) {
        item.item = null;
      }
      item.content = null;
      item.id = null;
    },

    // 过滤法规名称
    filteredLowsByType(type) {
      // 按类型过滤
      let filtered = this.lowsList;
      if (type) {
        filtered = filtered.filter(low => low.type === type);
      }
      return filtered;
    },

    // 处理法律类型变化（下拉选择时触发）
    handlelawTypeChange(item, val) {
      item.lawType = val; // 更新类型
    },

    // 处理法律类型输入（失去焦点时触发）
    handlelawTypeBlur(item, event) {
      item.lawType = event.target.value;
      item.lawName = null;
      item.lawsId = null;
      this.clearDependentFields(item, 1);
    },

    // 处理法律名称变化（下拉选择时触发）
    handlelawNameChange(item, val) {
      item.lawName = val; // 更新名称
      // 如果是从下拉框选择的，找到对应的法律ID
      if (val) {
        const selectedLaw = this.lowsList.find(
          law => law.name === val && law.type === item.lawType
        );
        item.lawsId = selectedLaw ? selectedLaw.id : null;
      }
    },

    // 处理法律名称输入（失去焦点时触发）
    handlelawNameBlur(item, event) {
      // 只有当是通过输入而不是选择时才处理
      if (event.target.value) {
        const isExisting = this.lowsList.some(
          law => law.name === event.target.value && law.type === item.lawType
        );
        if (!isExisting) {
          item.lawName = event.target.value;
          item.lawsId = null; // 手动输入时，清空ID
        } else {
          this.lowsList.forEach(low => {
            if (low.name === event.target.value && low.type === item.lawType) {
              item.lawsId = low.id;
              item.lawName = low.name;
            }
          })
        }
        this.clearDependentFields(item, 1);
        this.getArticleList(item)
      }
    },

    // 处理第几条变化（下拉选择时触发）
    handleArticleChange(item, val) {
      item.article = val; // 更新名称
      if (val) {
        const selectedArticle = this.articleList.find(
          article => article === val
        );
        item.article = selectedArticle ? selectedArticle : null;
      }
    },

    // 处理第几条输入（失去焦点时触发）
    handleArticleBlur(item, event) {
      // 只有当是通过输入而不是选择时才处理
      if (event.target.value) {
        const isExisting = this.articleList.some(
          article => article === event.target.value
        );
        if (!isExisting) {
          item.article = event.target.value;
        } else {
          this.articleList.forEach(article => {
            if (article === event.target.value) {
              item.article = article;
            }
          })
        }
        this.clearDependentFields(item, 2);
        this.getParagraphList(item)
      }
    },

    // 处理第几款变化（下拉选择时触发）
    handleParagraphChange(item, val) {
      item.paragraph = val; // 更新名称
      if (val) {
        const selectedParagraph = this.paragraphList.find(
          paragraph => paragraph === val
        );
        item.paragraph = selectedParagraph ? selectedParagraph : null;
      }
    },

    // 处理第几款输入（失去焦点时触发）
    handleParagraphBlur(item, event) {
      // 只有当是通过输入而不是选择时才处理
      if (event.target.value) {
        const isExisting = this.paragraphList.some(
          paragraph => paragraph === event.target.value
        );
        if (!isExisting) {
          item.paragraph = event.target.value;
        } else {
          this.paragraphList.forEach(paragraph => {
            if (paragraph === event.target.value) {
              item.paragraph = paragraph;
            }
          })
        }
        this.clearDependentFields(item, 3);
        this.getSubparagraphList(item)
      }
    },

    // 处理第几项变化（下拉选择时触发）
    handleSubparagraphChange(item, val) {
      item.subparagraph = val; // 更新名称
      if (val) {
        const selectedSubparagraph = this.subparagraphList.find(
          subparagraph => subparagraph === val
        );
        item.subparagraph = selectedSubparagraph ? selectedSubparagraph : null;
      }
    },

    // 处理第几项输入（失去焦点时触发）
    handleSubparagraphBlur(item, event) {
      // 只有当是通过输入而不是选择时才处理
      if (event.target.value) {
        const isExisting = this.subparagraphList.some(
          subparagraph => subparagraph === event.target.value
        );
        if (!isExisting) {
          item.subparagraph = event.target.value;
        } else {
          this.subparagraphList.forEach(subparagraph => {
            if (subparagraph === event.target.value) {
              item.subparagraph = subparagraph;
            }
          })
        }
        this.clearDependentFields(item, 4);
        this.getItemList(item)
      }
    },
    // 处理第几目变化（下拉选择时触发）
    handleItemChange(it, val) {
      if (val) {
        const selectedItem = this.itemList.find(
          item => item === val
        );
        let item = selectedItem ? selectedItem : null;
        if (item !== null) {
          it.item = item.item ? item.item : null;
          it.content = item.content ? item.content : null;
          it.id = item.id ? item.id : null;
        }
      }
    },

    // 处理第几目输入（失去焦点时触发）
    handleItemBlur(it, event) {
      // 只有当是通过输入而不是选择时才处理
      if (event.target.value) {
        const isExisting = this.itemList.some(
          item => item.item === event.target.value
        );
        if (!isExisting) {
          it.item = event.target.value;
          it.content = null;
          it.id = null;
        } else {
          this.itemList.forEach(item => {
            if (item.item === event.target.value) {
              it.item = item.item ? item.item : null;
              it.content = item.content ? item.content : null;
              it.id = item.id ? item.id : null;
            }
          })
        }
      }
    },

    // 新增违反条款项
    addIllegalTerms() {
      this.inputIllegalTermsObject.push({
        id: null,
        lawsId: null,
        article: null,
        paragraph: null,
        subparagraph: null,
        item: null,
        lawName: null,
        lawType: null,
        content: null
      });
    },
    // 删除违反条款项
    removeIllegalTerms(index) {
      this.inputIllegalTermsObject.splice(index, 1);
    },

    // 新增处罚依据项
    addIllegalBasis() {
      this.inputIllegalBasisObject.push({
        id: null,
        lawsId: null,
        article: null,
        paragraph: null,
        subparagraph: null,
        item: null,
        lawName: null,
        lawType: null,
        content: null
      });
    },
    // 删除处罚依据项
    removeIllegalBasis(index) {
      this.inputIllegalBasisObject.splice(index, 1);
    },

    // 新增法规
    addLawsAndRegulations() {
      this.isEdit = false
      this.dialogFormVisible = true
    },
    // 新增弹窗关闭
    CloseAddLawsAndRegulations() {
      this.dialogFormVisible = false
      // 清空数据
      this.lawsAndRegulationsForm = {
        illegalAct: null, // 违法行为
        illegalTerms: null, // 下拉框选择违反条款的ID
        illegalTermsObject: [], // 输入的违反条款
        illegalBasis: null, // 下拉框选择处罚依据的ID
        illegalBasisObject: [], // 输入的处罚依据
        slightPlotConsequences: null, // 轻微违法情节和后果
        slightPunishmentStandards: null, // 轻微处罚标准
        generalPlotConsequences: null, // 一般违法情节和后果
        generalPunishmentStandards: null, // 一般处罚标准
        seriousPlotConsequences: null, // 严重违法情节和后果
        seriousPunishmentStandards: null, // 严重处罚标准
      }
      this.inputIllegalTermsObject = [{
        id: null,
        lawsId: null, // 法律ID
        article: null, // 第几条
        paragraph: null, // 第几款
        subparagraph: null, // 第几项
        item: null, // 第几目
        lawName: null, // 法律名称
        lawType: null, // 法律类型
        content: null, // 条款内容
      }]
      this.inputIllegalBasisObject = [{
        id: null,
        lawsId: null, // 法律ID
        article: null, // 第几条
        paragraph: null, // 第几款
        subparagraph: null, // 第几项
        item: null, // 第几目
        lawName: null, // 法律名称
        lawType: null, // 法律类型
        content: null, // 条款内容
      }]
    },
    // 验证表单
    isValidate(form) {
      // 定义规则
      const rules = {
        illegalAct: [{ required: true, message: '请输入违法行为', trigger: 'blur' }],
        slightPlotConsequences: [{ required: true, message: '请输入轻微违法情节和后果', trigger: 'blur' }],
        slightPunishmentStandards: [{ required: true, message: '请输入轻微处罚标准', trigger: 'blur' }],
        generalPlotConsequences: [{ required: true, message: '请输入一般违法情节和后果', trigger: 'blur' }],
        generalPunishmentStandards: [{ required: true, message: '请输入一般处罚标准', trigger: 'blur' }],
        seriousPlotConsequences: [{ required: true, message: '请输入严重违法情节和后果', trigger: 'blur' }],
        seriousPunishmentStandards: [{ required: true, message: '请输入严重处罚标准', trigger: 'blur' }],
      }
      // 验证表单
      for (const key in rules) {
        if (rules.hasOwnProperty(key)) {
          const rule = rules[key];
          const value = form[key];
          if (!value) {
            this.$message({
              message: rule[0].message,
              type: 'warning'
            })
            return false;
          }
        }
      }
      // 验证违反条款项
      if (this.inputIllegalTermsObject.length > 0) {
        for (const item of this.inputIllegalTermsObject) {
          if (!item.lawType || !item.lawName || !item.article || !item.content) {
            this.$message({
              message: '违反条款项数据不完善',
              type: 'warning'
            })
            return false;
          }
        }
      }
      // 验证处罚依据项
      if (this.inputIllegalBasisObject.length > 0) {
        for (const item of this.inputIllegalBasisObject) {
          if (!item.lawType || !item.lawName || !item.article || !item.content) {
            this.$message({
              message: '处罚依据项数据不完善',
              type: 'warning'
            })
            return false;
          }
        }
      }
      return true;
    },

    saveLawsAndRegulations() {
      this.lawsAndRegulationsForm.illegalTermsObject = this.inputIllegalTermsObject
      this.lawsAndRegulationsForm.illegalBasisObject = this.inputIllegalBasisObject
      console.log(this.lawsAndRegulationsForm)

      // 验证表单
      if (!this.isValidate(this.lawsAndRegulationsForm)) {
        return
      }

      // 向后端传输数据
      request.post('/laws-and-regulations/edit', this.lawsAndRegulationsForm).then(res => {
        if (res.code === '200' && res.data === true) {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.CloseAddLawsAndRegulations()
          // 更新数据
          this.load()
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },
    // 删除法规
    deleteRoleData(id) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get(`/laws-and-regulations/delete/${id}`).then(res => {
          if (res.code === '200') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            // 更新数据
            this.load()
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        })
      }).catch(() => {
        this.$message({
          message: '已取消删除',
          type: 'info'
        })
      })
    },
    // 编辑法规
    editRoleData(row) {
      this.isEdit = true;
      this.lawsAndRegulationsForm = { ...row };

      request.get(`/laws-and-regulations/getTermObjectList`, {
        params: {
          illegalTermsIds: row.illegalTerms,
          illegalBasisIds: row.illegalBasis,
        },
        paramsSerializer: (params) => {
          return Object.entries(params)
            .flatMap(([key, values]) =>
              Array.isArray(values)
                ? values.map(value => `${key}=${encodeURIComponent(value)}`)
                : `${key}=${encodeURIComponent(values)}`
            )
            .join('&');
        }
      }).then(res => {
        if (res.code === '200') {
          this.inputIllegalTermsObject = res.data.illegalTermsObject
          this.inputIllegalBasisObject = res.data.illegalBasisObject
        }
      })
      this.dialogFormVisible = true
    },

    // 判断第几条是否可编辑
    isArticleEditable(item) {
      if (item.id) {
        return true
      }
      if (!item.lawName) {
        return true
      }
      return false
    },

    // 判断第几款是否可编辑
    isParagraphEditable(item) {
      if (item.id) {
        return true
      }
      if (!item.article) {
        return true
      }
      return false
    },
    // 判断第几项是否可编辑
    isSubparagraphEditable(item) {
      if (item.id) {
        return true
      }
      if (!item.paragraph) {
        return true
      }
      return false
    },
    // 判断第几目是否可编辑
    isItemEditable(item) {
      if (item.id) {
        return true
      }
      if (!item.subparagraph) {
        return true
      }
      return false
    },
    // 判断内容是否可编辑
    isContentEditable(item) {
      if (item.id) {
        return true
      }
      if (!item.article) {
        return true
      }
      return false
    }
  }
}
</script>

<style scoped>
#roleSpan {
  color: black;
  text-decoration: none;
}

/*   外框架   */
.framework1 {
  height: calc(100vh - 88px);
  width: calc(100vh - 200px);
  margin-left: 8px;
  border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
  height: calc(100vh - 92px);
  border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
  font-size: 16px;
  font-weight: bold;
  padding: 4px 20px;
  background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
  padding: 4px 10px;
  background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
  padding: 4px 10px;
  background-color: #f4f3f9;
}


.formatted-text {
  text-align: left;
  white-space: pre-wrap;
}
</style>
